import axios from "axios";
// token
import {useUserStore} from "@/store/modules/user.ts";
// tokenName
import {tokenName, loginPageURL} from "@/config/globalConfig.ts";
// 引入提示
import { showToast } from 'vant';

// 基地址
const baseURL = import.meta.env.VITE_API_BASE_URL;

const request = axios.create({
    baseURL, // url = base url + request url
    timeout: 10000,// request timeout
    // withCredentials:true
});
// 引入路由
import router from "@/router";
// 引入加密
import {encode} from "@/utils/utils.ts";

// 请求拦截
request.interceptors.request.use(
    (config: any) => {
        const userStore = useUserStore();
        let headers: {
            [index: string]: any
        } = {};
        if(userStore && userStore.token) headers[tokenName] = userStore.token;
        return {
            ...config,
            headers
        }
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// 响应拦截
request.interceptors.response.use(
    (response: any) => {
        const res = response.data;
        // 成功相应码时直接返回
        if(res.code === 200) return res;
        // 未登录跳转重新登录即可，就不用router.replace
        else if(res.code === 401) {
            const route = router.currentRoute.value;
            const encodeURL = encode(route.fullPath);
            const userStore = useUserStore();
            userStore.clearUserInfo();
            showToast({
                message: '未登录'
            });
            router.push({path: loginPageURL, query: {redirect: encodeURL}});
        } else {
            console.error("未经错误定义的返回");
            return res;
        }

        // if (res.code !== 1 || res.code !== 200) {
        //     console.log("进入了错误阶段");
        //
        //     return Promise.reject(res);
        //     return response.data
        // } else {
        //     return response.data
        // }
    },
    (error: any) => {
        console.log(error)
        if (error.response) {
            switch (error.response.code) {
                case 500:
                    // ElMessage({
                    //     message: "服务器错误，请稍后重试",
                    //     type: "error",
                    //     duration: 5 * 1000
                    // })
                    break;
                default:
                    if (error.response.data.error == "invalid_grant") {
                        // ElMessage({
                        //     message: error.response.data.error_description,
                        //     type: "error"
                        // })
                    }
                    return Promise.reject(error)
            }
        }
    }
)

export default request;